/* ----------------------- 本地存储相关 ----------------------- */

/* 从本地缓存中异步获取指定key的内容 */
const getStorage = key => new Promise((resolve, reject) => {
  wx.getStorage({
    key: key,
    success: res => {
      resolve(res.data)
    },
    fail: e => {
      reject(e)
    },
    complete: () => {}
  })
})

/*
  将数据存储在本地缓存中指定的key中。覆盖原来的key
  数据生命周期与小程序本身一致：用户主动删除或超过一定时间
  10MB
*/
const setStorage = (key, value) => new Promise((resolve, reject) => {
  wx.setStorage({
    key: key,
    data: value,
    success: () => {
      resolve()
    },
    fail: e => {
      reject(e)
    }
  })
})

/*
  从本地缓存中移除指定key
*/
const removeStorage = key => new Promise((resolve, reject) => {
  wx.removeStorage({
    key: key,
    success: res => {
      resolve(res.data)
    },
    fail: (e) => {
      reject(e)
    }
  })
})

/*
  清除本地缓存
*/
const clearStorage = () => new Promise((resolve, reject) => {
  try {
    wx.clearStorageSync()
    resolve()
  } catch (e) {
    reject(e)
  }
})

/* ----------------------- 授权相关 ----------------------- */

/*
  获取登录凭证 code
*/
const login = () => new Promise((resolve, reject) => {
  wx.login({
    success: res => {
      resolve(res)
    },
    fail: e => {
      reject(e)
    }
  })
})

/*
  检查登录状态是否过期
*/
const checkSession = () => new Promise((resolve, reject) => {
  wx.checkSession({
    success: function () {
      // session_key 未过期，并且在本生命周期一直有效
      resolve(true)
    },
    fail: function () {
      // session_key 已经失效，需要重新执行登录流程
      resolve(false)
    }
  })
})

/*
  获取用户信息
  调用前需要使用<button open-type="getUserInfo"/> 授权
*/
const getUserInfo = () => new Promise((resolve, reject) => {
  wx.getUserInfo({
    withCredentials: true,
    success: res => {
      resolve(res)
    },
    fail: e => {
      reject(e)
    }
  })
})

/* ----------------------- 其他  ----------------------- */

/*
  扫码
  onlyFromCamera  false 是否只能从相机扫码，不允许从相册选择图片
  scanType ['barCode', 'qrCode'] 扫码类型
*/
const handleScan = () => new Promise((resolve, reject) => {
  wx.scanCode({
    success: res => {
      resolve(res)
    },
    fail: e => {
      reject(e)
    }
  })
})

/* ----------------------- 交互  ----------------------- */

/*
  显示模态对话框
  isCancel 是否显示取消按钮
*/
const showModal = (title, content, isCancel = false) => new Promise(resolve => {
  wx.showModal({
    title,
    content,
    showCancel: isCancel,
    cancelText: '取消', // 最多4个字符
    confirmText: '确定', // 最多4个字符
    success: res => {
      if (res.confirm) {
        resolve('ok')
      } else if (res.cancel) {
        resolve('cancel')
      }
    }
  })
})

/*
  显示消息提示框
  icon 的值 success title 7个汉字
            loading title 7
            none  两行
*/
const toast = (content, icon = 'none', duration = 4000, mask = false) => new Promise((resolve, reject) => {
  wx.showToast({
    title: content,
    icon,
    duration,
    mask,
    success: res => {
      resolve(res)
    },
    fail: e => {
      reject(e)
    }
  })
})

/*
  模态框模拟alert
*/
const alert = (content, confirmText = '确定') => new Promise((resolve, reject) => {
  wx.showModal({
    title: '',
    content,
    showCancel: false,
    confirmText,
    success: function (res) {
      resolve(res)
    },
    fail: function (e) {
      reject(e)
    }
  })
})

/*
  显示 loading 提示框
*/
const showLoading = (title = '加载中') => new Promise((resolve, reject) => {
  wx.showLoading({
    title,
    mask: true,
    success: res => {
      resolve(res)
    },
    fail: e => {
      reject(e)
    }
  })
})

/*
  隐藏loading
*/
const hideLoading = () => wx.hideLoading()

/*
  显示当前页面的转发按钮
*/
const showShareMenu = () => wx.showShareMenu()

/*
  将页面滚动到目标位置
  scrollTop num 单位px
  duration  num 300
*/
const pageScrollTo = () => wx.pageScrollTo

/* ----------------------- 路由 ---------------------- */

/*
  保留当前页面，跳转到应用内的某个页面。但是不能跳到 tabbar 页面。使用 wx.navigateBack 可以返回到原页面。
*/
const navigateTo = url => {
  wx.navigateTo({
    url
  })
}

/*
  关闭当前页面，返回上一页面或多级页面。可通过 getCurrentPages() 获取当前的页面栈，决定需要返回几层。
*/

const navigateBack = delta => {
  wx.navigateBack({
    delta
  })
}

/*
  关闭当前页面，跳转到应用内的某个页面。但是不允许跳转到 tabbar 页面。
*/
const redirectTo = url => {
  wx.redirectTo({
    url
  })
}

/*
  跳转到 tabBar 页面，并关闭其他所有非 tabBar 页面
  '/index'
*/
const switchTab = url => {
  wx.switchTab({
    url
  })
}

/*
  关闭所有页面，打开到应用内的某个页面
*/
const reLaunch = url => {
  wx.reLaunch({
    url
  })
}

/* -------------- 下拉 ---------------- */

/*
  开始下拉刷新。调用后触发下拉刷新动画，效果与用户手动下拉刷新一致。
*/
const startPullDownRefresh = () => new Promise((resolve, reject) => {
  wx.startPullDownRefresh({
    success (res) {
      resolve(res)
    },
    fail (e) {
      reject(e)
    }
  })
})

/*
  停止当前页面下拉刷新。
*/
const stopPullDownRefresh = () => new Promise((resolve, reject) => {
  wx.stopPullDownRefresh({
    success (res) {
      resolve(res)
    },
    fail (e) {
      reject(e)
    }
  })
})

/*
  获取网络类型
  networkType: wifi 2g 3g 4g unknown none
*/
const checkNetWork = () => new Promise((resolve, reject) => {
  wx.getNetworkType({
    success: function (res) {
      let networkType = res.networkType
      if (networkType === 'none' || networkType === 'unknown') {
        resolve(false)
      } else {
        resolve(true)
      }
    },
    fail: function (e) {
      resolve(false)
    }
  })
})

export {
  getStorage,
  setStorage,
  removeStorage,
  clearStorage,
  login,
  checkSession,
  getUserInfo,
  handleScan,
  showModal,
  toast,
  alert,
  showLoading,
  hideLoading,
  showShareMenu,
  pageScrollTo,
  navigateTo,
  navigateBack,
  redirectTo,
  switchTab,
  reLaunch,
  startPullDownRefresh,
  stopPullDownRefresh,
  checkNetWork
}
